require 'digest/sha1'
module Compartido
  # Uniqueness of username in both Alumno and Profesor  
  def validate_on_create
    if Alumno.find_by_username(username) || Profesor.find_by_username(username)
      errors.add_to_base("El nombre de usuario ya está en uso") 
    end
  end 
  
  def clave 
    @clave 
  end

  def clave=(pwd) 
    @clave = pwd 
    return if pwd.blank? 
    create_new_salt 
    self.password = encrypted_password(self.clave, self.salt) 
  end
  
  def human_name
    "#{self.nombre} #{self.ap_paterno} #{self.ap_materno}"
  end
    
  private
  
  def create_new_salt 
    self.salt = self.object_id.to_s + rand.to_s 
  end 
  
	def encrypted_password(clave, salt) 
    string_to_hash = clave + "wibble" + salt # 'wibble' makes it harder to guess 
    Digest::SHA1.hexdigest(string_to_hash) 
  end
  
end
